package org.jz.gae.redbook.spb.client.toolkit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class SlateListPanel extends Composite
{
	private ApplicationAgent applicationAgent;
	private VerticalPanel rootPanel = new VerticalPanel();
	private VerticalPanel slateListPanel = new VerticalPanel();
	private List<Slate> slateList;
	private Button activeButton;
	private Map<Button, Slate> buttonSlateMap = new HashMap<Button, Slate>(); 
	private Map<Slate, Button> slateButtonMap = new HashMap<Slate, Button>(); 
	
	public SlateListPanel() 
	{
		SimplePanel contentTableDecorator = new SimplePanel();
	    initWidget(contentTableDecorator);
	    contentTableDecorator.setWidth("100%");
		initializeInterface();
	    contentTableDecorator.add(rootPanel);
	}

	private void initializeInterface()
	{
		rootPanel.setWidth("100%");
    		slateListPanel.addStyleName("applicationSlateListBody");
		    slateListPanel.setWidth("100%");
		rootPanel.add(slateListPanel);
	}
	
	public void setSlateList(
			List<Slate> slateList)
	{
		this.slateList = slateList;
	}
	
	public void setApplicationAgent(
			ApplicationAgent applicationAgent)
	{
		this.applicationAgent = applicationAgent;
	}

	public void reflectSlateActivation(
			Slate _Slate)
	{
		if (this.activeButton != null)
		{
    		this.activeButton.removeStyleName("activeSlateButton");
		}
		this.activeButton = slateButtonMap.get(_Slate);
		if (this.activeButton != null)
		{
    		this.activeButton.addStyleName("activeSlateButton");
		}
	}

	public void reflectSlateAppending(
			final Slate _NewSlate)
	{
		final Button slateButton = new Button(_NewSlate.getTitle());
		slateButton.setWidth("100%");
		slateButton.addClickHandler(new ClickHandler(){
			private Button localButton;
			{
				localButton = slateButton;
			}
			@Override
			public void onClick(ClickEvent event)
			{
				if (localButton != activeButton)
				{
				    applicationAgent.reactivateSlate(_NewSlate);
				}
			}
		});
		slateButtonMap.put(_NewSlate, slateButton);
		buttonSlateMap.put(slateButton, _NewSlate);
		slateListPanel.add(slateButton);
	}
	
	public void reflectSlateClosing(
			final Slate _OldSlate)
	{
		Button slateButton = slateButtonMap.get(_OldSlate);
		slateButtonMap.remove(_OldSlate);
		buttonSlateMap.remove(slateButton);
		slateListPanel.remove(slateButton);
	}
}
